package club.kingyin.kyblogprofile.controller;

import club.kingyin.commons.constant.AuthorizeConstant;
import club.kingyin.commons.entity.file.File;
import club.kingyin.commons.enums.BlogEnum;
import club.kingyin.commons.response.ResultCode;
import club.kingyin.commons.utils.SizeUtils;
import club.kingyin.easycache.annotation.EasyCache;
import club.kingyin.kyblogprofile.core.cache.ShareFileHandler;
import club.kingyin.kyblogprofile.core.cache.UpdateShareFolderHandler;
import club.kingyin.kyblogprofile.entity.FilePram;
import club.kingyin.kyblogprofile.service.BucketService;
import club.kingyin.kyblogprofile.service.FileService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import club.kingyin.commons.response.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/file/bucket")
public class BucketController {

    @Autowired
    private BucketService bucketService;

    @Resource
    private FileService fileService;

    @GetMapping("/list")
    public Result getBuckets() {
        Result buckets = bucketService.buckets();
        return buckets == null ? Result.fail("700","服务异常"):buckets;
    }

    @GetMapping("/exists")
    public Result exists(@RequestParam("bucketName") String bucketName) {
        Result contains = bucketService.contains(bucketName);
        return contains == null ? Result.fail("701","服务异常"):contains;
    }


    @EasyCache(prams = {"userid","filePram.path","filePram.bucket","id=filePram.id"}, module = "ky-file", handler = {ShareFileHandler.class})
    @PostMapping("/files")
    public Result list(@RequestHeader(AuthorizeConstant.ID) Integer userid, @RequestBody FilePram filePram) {
        if ("root".equals(filePram.getBucket())) {
            return Result.success(bucketService.foldersByBucketName("cloud", filePram.getPath(), true));
        }
        if ("world".equals(filePram.getBucket())) {
            return Result.success(bucketService.foldersByBucketName("cloud", filePram.getPath(), false));
        }
        return Result.success(bucketService.filesByBucketName(filePram.getBucket(), createPath(userid,filePram.getPath())));
    }

    @EasyCache(handler = {UpdateShareFolderHandler.class})
    @EasyCache(prams = {"userid"}, delete = {"ky-file:list"})
    @EasyCache(prams = {"id=userid"}, delete = {"list"}, module = "ky-file")
    @GetMapping("/create")
    public Result mkdir(@RequestHeader(AuthorizeConstant.ID) int userid,@RequestParam("bucket") String bucket, @RequestParam("path") String path, @RequestParam("newFolder") boolean newFolder) {
        bucketService.mkdir(bucket, createPath(userid,path));
        if (newFolder) {
//            bucketService.mkdir(bucket, createPath(userid,"@kingyin.txt"));
        }
        return Result.success(null,"创建成功");
    }

    @EasyCache(prams = {"userid"}, delete = {"ky-file:list"})
    @EasyCache(prams = {"id=userid"}, delete = {"list"}, module = "ky-file")
    @PostMapping("/remove")
    public Result remove(@RequestHeader(AuthorizeConstant.ID) int userid,@RequestBody FilePram filePram) {
        bucketService.remove(filePram.getBucket(), createPath(userid, filePram.getPath()));
        return Result.infoN("删除成功");
    }

    @PostMapping("/upload/system")
    public Result uploadBySystem(@RequestPart("file") MultipartFile file, @RequestParam("path") String path, @RequestParam("bucket") String bucket) {
        //获取文件流
        try {
            InputStream is = file.getInputStream();
            //获取文件名称
            String filename = file.getOriginalFilename();
            //获取文件类型
            String contentType = file.getContentType();
            String url = bucketService.uploadFileInputStream(bucket, path, is, contentType,false);
            return getUploadResult(filename, url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.failR("上传失败");
    }

    private Result getUploadResult(String filename, String url) {
        if (url != null) {
            Result result = new Result();
            result.setCode(ResultCode.INFO_NOTIFY.val());
            result.setData(url);
            result.setMessage(filename+" 上传成功");
            return result;
        }
        return Result.failR(filename+" 上传失败");
    }

    @EasyCache(prams = {"userid"}, delete = {"ky-file:list"})
    @EasyCache(prams = {"id=userid"}, delete = {"list"}, module = "ky-file")
    @PostMapping("upload")
    public Result uploadResource(@RequestHeader(AuthorizeConstant.ID) int userid,@RequestParam(value = "file") MultipartFile file, @RequestParam("path") String path) {
        if (!SizeUtils.checkFileSize(file.getSize(), 20, SizeUtils.SizeUnit.MB)) {
            // 文件超过20M
            return Result.infoN("文件大小超过20M");
        }
        //获取文件流
        try {
            InputStream is = file.getInputStream();
            //获取文件名称
            String filename = file.getOriginalFilename();
            //获取文件类型
            String contentType = file.getContentType();
            String url = bucketService.uploadFileInputStream("cloud", createPath(userid, path + filename), is, contentType,true);
            return getUploadResult(filename, url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.failR("上传失败");
    }

    @EasyCache(prams = {"userid"} ,delete = {"list"}, module = "ky-file")
    @EasyCache(prams = {"userid"}, delete = {"getShareInfo"}, module = "ky-file")
    @EasyCache(prams = {"id=userid"}, delete = {"list","getShareInfo"}, module = "ky-file")
    @PostMapping("/share")
    public Result shareChange(@RequestHeader(AuthorizeConstant.ID) int userid,@RequestBody() File file) {
        if (!file.getPath().startsWith(String.valueOf(userid))) {
            Result.failR("无权操作");
        }
        file.setId(userid);
        if (file.getStatus() == BlogEnum.NOT_SHARE) {
            // 取消
            LambdaQueryWrapper<File> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(File::getPath, file.getPath());
            if (fileService.count(queryWrapper) == 0) {
                return fileService.save(file)?Result.infoN("已取消该项的共享设置"):Result.failR("操作失败");
            }
            LambdaUpdateWrapper<File> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(File::getPath, file.getPath()).set(File::getStatus,BlogEnum.NOT_SHARE);
            return fileService.update(updateWrapper)?Result.infoN("已取消该项的共享设置"):Result.failR("操作失败");
        } else {
            // 共享
            LambdaQueryWrapper<File> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(File::getPath, file.getPath());
            if (fileService.count(queryWrapper) == 0) {
                return fileService.save(file)?Result.infoN("已共享该项"):Result.failR("操作失败");
            }
            LambdaUpdateWrapper<File> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(File::getPath, file.getPath()).set(File::getStatus,file.getStatus());
            return fileService.update(updateWrapper)?Result.infoN("已共享该项"):Result.failR("操作失败");
        }
    }
    @EasyCache(prams = {"userid"}, module = "ky-file")
    @GetMapping("/share/info")
    public Result getShareInfo(@RequestHeader(AuthorizeConstant.ID) int userid, @RequestParam("path") String path) {
        LambdaQueryWrapper<File> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.likeRight(File::getPath, userid+path).select(File::getPath,File::getStatus);
        return Result.success(fileService.list(queryWrapper));
    }

    public String createPath(int id, String path) {
        return "/" + id + path;
    }

}
